<template>
   <a-spin class="spin-text"  :spinning="resetRuleDataLoading" tip="正在重置校验数据中(约20s)...">  
    <!-- <span class="spin-text">加载中...</span> -->
    <div class="flex-box" v-if="workTypeInfo.workTypeArr.length > 0">
      <div class="flex-box-left">
        <div class="pl20">
          <span class="radio-label">工作类型：</span>
          <el-radio-group v-model="workTypeInfo.workType">
            <el-radio
              v-for="(item, index) in workTypeInfo.workTypeArr"
              :value="item.workTypeValue"
              :key="item.workTypeValue"
            >
              {{ item.workTypeLabel }}
            </el-radio>
          </el-radio-group>
        </div>
        <div class="upload-demo-box">
          <el-upload
            drag
            v-model="fileList"
            name="file"
            :multiple="true"
            @change="handleChange"
            :before-upload="beforeUpload"
          >
            <p class="ant-upload-drag-icon">
              <inbox-outlined></inbox-outlined>
            </p>
            <p class="ant-upload-text">点击进行上传或拖拽文件到此处</p>
          </el-upload>
        </div>
      </div>
      <div class="flex-box-right">
        <div class="serach-box">
          <div>
            <el-input
              v-model="searchText"
              style="max-width: 400px"
              placeholder="请输入文件名称搜索"
              class="input-with-select"
              autofocus
              @keyup.enter="onSearch"
            >
              <template #append>
                <el-button :icon="SearchIcon" />
              </template>
            </el-input>
            <a-button @click="openChcekSystem('本地')" :hidden="!isDev">
              打开本地校验系统
            </a-button>
            <a-button @click="openChcekSystem('在线')">
              打开在线系统
            </a-button>
            <a-button @click="resetRuleData"  :loading="resetRuleDataLoading">
              重置本地校验规则数据
          </a-button>          
            <a-button @click="clearCache">
              清除应用缓存
          </a-button>          
          </div>
        </div>
        <div class="table-area">
          <a-table
            :columns="columns"
            :data-source="jiaoyanjieguoTable"
            :rowKey="(record) => record.tableId"
            :pagination="{ pageSize: 15 }"
            :scroll="{ x: 200, y: tableScrollY }"
          >
            <!-- :scroll="{ x: 200,y: 600 }" -->
            <template #jiaoyanjieguo="{ record }">
              <div>
                <span
                  :class="
                    record.jiaoyanjieguo.checkStatus === '0'
                      ? 'blue-color'
                      : 'red-color'
                  "
                  >{{
                    record.jiaoyanjieguo.checkStatus === "0" ? "通过" : "不通过"
                  }}</span
                >
              </div>
            </template>
            <template #operation="{ record }">
              <a-popconfirm
                v-if="jiaoyanjieguoTable.length"
                title="是要删除吗?"
                cancelText="取消"
                okText="确定"
                @confirm="onDelete(record)"
              >
                <a>删除</a>
              </a-popconfirm>
            </template>
            <template #jiaoyanjieguoDetail="{ record }">
              <div>
                <a @click="onDetail(record)">校验结果详情</a>
              </div>
            </template>
          </a-table>
        </div>
      </div>
      <el-dialog
        v-model="dialogVisible"
        title="校验结果详情"
        width="1200"
        :before-close="handleClose"
      >
        <el-table
          :data="curRecord.jiaoyanjieguo.checkData"
          style="width: 100%"
          :row-class-name="tableRowClassName"
          height="500"
        >
          <el-table-column prop="key" label="参数" width="400" />
          <el-table-column prop="value" label="值" />
          <el-table-column prop="expected" label="期望值" />
          <el-table-column prop="status" label="校验">
            <template #default="scope">
              <div>{{ scope.row.status === "0" ? "通过" : "不通过" }}</div>
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <div class="dialog-footer">
            <!-- <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="dialogVisible = false">
            Confirm
          </el-button> -->
          </div>
        </template>
      </el-dialog>
    </div>
    <div v-else> 
      <el-empty description="离线功能需要先在有网情况下登录系统，在校验结果节点点击【下载校验规则数据到客户端】后才能使用">
        <a-button @click="openChcekSystem('在线')">
              打开在线系统
        </a-button>
        <!--  hidden="!location.href.inludes('localhost')" -->
        <a-button @click="openChcekSystem('本地')" hidden>
              打开本地校验系统
            </a-button>     
        <a-button @click="init">
              刷新
        </a-button>
        <a-button @click="resetRuleData" :loading="resetRuleDataLoading">
            重置本地校验规则数据
        </a-button>
        <a-button @click="clearCache">
              清除应用缓存
        </a-button>
      </el-empty>
    </div>
  </a-spin>
</template>
  <script>
import { InboxOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { defineComponent, ref } from "vue";
import { ipcApiRoute } from "@/api/main";
import { ipc } from "@/utils/ipcRenderer";
import { toRaw, onMounted } from "vue";
import { checkFiles, parseFiles, formatDateTime,calculateHash } from "./format";
import { Search as SearchIcon } from "@element-plus/icons-vue";
// const leno_admin = require('../../../../../data/leno_admin.json')
// import leno_admin from '../../../../../data/leno_admin.json'
export default defineComponent({
  components: {
    InboxOutlined,
  },
  setup() {
    let guizeRes = [];
    const returnRes = {
      isDev: window.location.href.includes("localhost"),
      workTypeInfo: ref({ workType: "", workTypeArr: [] }),
      fileList: ref([]),
      searchText: ref(""),
      jiaoyanjieguoTable: ref([]),
      tableScrollY: ref(500),
      dialogVisible: ref(false),
      resetRuleDataLoading: ref(false),
      curRecord: ref({}),
      SearchIcon,
    };
    window.returnRes = returnRes;
    const onSearch = () => {
      queryjiaoyanjieguoTable({
        original_filename: returnRes.searchText.value,
      });
    };
    const beforeUpload = (file) => {
      return false;
    };
    const handleClose = () => {
      returnRes.dialogVisible.value = false;
      return true;
    };
    const onDetail = (record) => {
      returnRes.curRecord.value = record;
      returnRes.dialogVisible.value = true;
    };
    const queryjiaoyanjieguoTable = (searchParam = {}) => {
      ipc
        .invoke(ipcApiRoute.lenodbOperation, {
          tableName: "jiaoyanjieguo_table",
          action: "getAll",
          searchParam,
        })
        .then((res) => {
          res.result.forEach((item) => {
            item.jiaoyanjieguo = JSON.parse(item.jiaoyanjieguo);
          });
          res.result.sort((prev, next) => {
            let res =
              new Date(prev.created_at).getTime() -
              new Date(next.created_at).getTime();
            return res > 0 ? -1 : 1;
          });

          returnRes.jiaoyanjieguoTable.value = res.result;
        });
    };
    const handleChange = (info) => {
      const status = info.raw.status;
      let fileSuffix = info.raw.name.split(".")[1];
      let nameSplit = info.raw.name.split('.')
        let houzhui = nameSplit[nameSplit.length - 1] 
      if (status !== "uploading") {
        // console.log(info.raw, info.rawList);
      }
      if (status === "done") {
        message.success(`${info.raw.name} file uploaded successfully.`);
      } else if (status === "error") {
        message.error(`${info.raw.name} file upload failed.`);
      }
      const reader = new FileReader();
      reader.onload = async function (e) {
        const fileContent = e.target.result;
        let new_filename = await calculateHash(info.raw)
        let fileName = info.raw.name;
        fileName = fileName.replace(/\s/g, "");
        let resultData = parseFiles(fileContent, fileName);
        let currentfileRules = guizeRes.filter(
          (item) =>
            item.deviceName == fileName &&
            item.workType == returnRes.workTypeInfo.value.workType
        );
        if (currentfileRules.length == 0) {
          return message.warning(`${fileName} 没有对应校验规则，请到线上环境确认`);
        }
        const { checkData, checkStatus } = checkFiles(resultData,currentfileRules );
        const check_result_status = checkStatus === "0" ? "1" : "0";
        let row = {
          tableId: Date.now()+'',
          filepath: "",
          original_filename: fileName,
          new_filename,
          jiaoyanjieguo: JSON.stringify({ checkData, checkStatus }),
          check_result: check_result_status, // 审核结果状态
          dept_id: "",
          created_at: formatDateTime(Date.now()),
        };
        ipc
          .invoke(ipcApiRoute.lenodbOperation, {
            tableName: "jiaoyanjieguo_table",
            action: "add",
            addParam: row,
          })
          .then(() => {
            queryjiaoyanjieguoTable();
          });
      };
      reader.readAsText(info.raw);
    };
    const openChcekSystem = (type) => {
      let urlMap = {
        本地: {
          type: "web",
          content: "http://localhost:9091/",
        },
        在线: {
          type: "web",
          content: "http://49.232.158.183/",
        },
      };
      ipc.invoke(ipcApiRoute.createWindow, toRaw(urlMap[type])).then((r) => {
        console.log(r);
      });
    };
    const onWindowResize = () => {
      let searchBox = document.querySelector(".serach-box")
      if (searchBox) {
        returnRes.tableScrollY.value =
          window.innerHeight -
          searchBox.clientHeight -
          120;
      }
    };

    const init = () => {
      ipc
        .invoke(ipcApiRoute.lenodbOperation, {
          tableName: "gongzuoleixing_table2",
          action: "getAll",
        })
        .then((res) => {
          returnRes.workTypeInfo.value.workTypeArr = res.result;
          // returnRes.workTypeInfo.value.workTypeArr = [];
          returnRes.workTypeInfo.value.workType = res.result[0].workTypeValue;
        });
      ipc
        .invoke(ipcApiRoute.lenodbOperation, {
          tableName: "jiaoyanguize_table",
          action: "getAll",
        })
        .then((res) => {
          guizeRes = res.result;
        });
        queryjiaoyanjieguoTable();
        ipc.invoke(ipcApiRoute.getAppInfo, {
          })
          .then((res) => {
            // 获取应用程序版本
            let {version} = res
            let curVersion = localStorage.getItem('appVersion')
            if (curVersion != version) {
              // 自动执行重置本地校验规则数据
              resetRuleData()
              // 更新应用程序版本
              localStorage.setItem('appVersion',version)
            }
          });
    }
    onMounted(() => {
      init();
      onWindowResize();
      window.addEventListener("resize", () => {
        onWindowResize();
      });
    });
    /* 
          filepath: "",
          original_filename: info.raw.name,
          new_filename: "fileId",
          jiaoyanjieguo: JSON.stringify(checkData),
          check_result: check_result_status, // 审核结果状态
          dept_id: "",
*/
    const columns = [
      {
        title: "文件名称",
        dataIndex: "original_filename",
        key: "original_filename",
        width: "250px",
      },
      {
        title: "校验结果",
        dataIndex: "jiaoyanjieguo",
        key: "jiaoyanjieguo",
        width: "100px",
        slots: {
          customRender: "jiaoyanjieguo",
        },
      },
      {
        title: "校验结果详情",
        dataIndex: "jiaoyanjieguoDetail",
        key: "jiaoyanjieguoDetail",
        width: "150px",
        slots: {
          customRender: "jiaoyanjieguoDetail",
        },
      },
      {
        title: "创建时间",
        dataIndex: "created_at",
        key: "created_at",
        width: "250px",
        slots: {
          customRender: "created_at",
        },
      },
      {
        title: "操作",
        dataIndex: "operation",
        fixed: "right",
        width: "150px",
        slots: {
          customRender: "operation",
        },
      },
    ];
    const onDelete = (record) => {
      ipc
        .invoke(ipcApiRoute.lenodbOperation, {
          tableName: "jiaoyanjieguo_table",
          action: "del",
          delParam: { tableId: record.tableId },
        })
        .then(() => {
          queryjiaoyanjieguoTable();
        });
    };
    const tableRowClassName = ({ row, rowIndex }) => {
      return row.status === "1" ? "warning-row" : "";
    };
    const clearCache = () => {
      ipc
        .invoke(ipcApiRoute.clearCache)
        .then((res) => {
        });      
    }
    const resetRuleData = async () => {
      try {
        
        returnRes.resetRuleDataLoading.value = true
        let leno_admin = await import('../../../../../data/leno_admin.json')
        
        await ipc.invoke(ipcApiRoute.updateLenoAdminJSON, {leno_admin:leno_admin.default})
        message.success(`重置本地校验规则数据成功`);
        returnRes.resetRuleDataLoading.value = false
      } catch (error) {
        message.error(`重置本地校验规则数据失败`);
        returnRes.resetRuleDataLoading.value = false
      }
    }
    return {
      ...returnRes,
      columns,
      onDelete,
      openChcekSystem,
      handleChange,
      beforeUpload,
      queryjiaoyanjieguoTable,
      onSearch,
      handleClose,
      onDetail,
      tableRowClassName,
      init,
      resetRuleData,
      clearCache,
    };
  },
});
</script>

<style lang="less">
.ant-spin-text {
  font-size: 24px !important;
}
</style>
<style lang="less" scoped>
.spin-text {
}
.ant-spin-text {
  font-size: 30px !important;
}
.pl20 {
  padding-left: 20px;
  padding-top: 20px;
}
.item-li {
  > span {
    margin-right: 20px;
  }
}
.flex-box {
  text-align: left;
  height: 100%;
  display: flex;
  overflow: hidden;
  .flex-box-left {
    flex-basis: 300px;
    border-right: 1px solid #ccc;
    flex-shrink: 0;
    padding: 10px;
  }
  .flex-box-right {
    padding: 10px;
    flex: 1;
    display: flex;
    flex-direction: column;
    .serach-box {
      flex-basis: 60px;
      padding: 10px 0;
      .ant-btn {
        margin-left: 10px;
      }
    }
    .table-area {
      flex: 1;
      // overflow: auto;
      .ant-table-wrapper {
        height: 100%;
      }
    }
  }
}
.blue-color {
  color: blue;
}
.red-color {
  color: red;
}
.radio-label {
  vertical-align: text-bottom;
}
</style>
<style>
.warning-row {
  color: red;
}
</style>